package org.asiainfo.common.satoken.utils;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.asiainfo.common.core.constant.TenantConstants;
import org.asiainfo.common.core.constant.UserConstants;
import org.asiainfo.common.core.enums.UserType;
import org.asiainfo.system.api.model.LoginUser;

import java.util.Set;
import java.util.function.Supplier;

import static org.asiainfo.common.core.constant.CacheNames.*;

/**
 * 登录用户工具类
 *
 * @author dotor-ww
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LoginHelper {

    /**
     * 获取用户id
     */
    public static Long getUserId() {
        return Convert.toLong(getExtra(USER_KEY));
    }

    /**
     * 获取部门ID
     */
    public static Long getDeptId() {
        return Convert.toLong(getExtra(DEPT_KEY));
    }

    private static Object getExtra(String key) {
        return getStorageIfAbsentSet(key, () -> StpUtil.getExtra(key));
    }

    /**
     * 获取用户账户
     */
    public static String getUsername() {
        return Convert.toStr(getExtra(USER_NAME_KEY));
    }

    /**
     * 获取用户类型
     */
    public static UserType getUserType() {
        String loginId = StpUtil.getLoginIdAsString();
        return UserType.getUserType(loginId);
    }

    /**
     * 是否为超级管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isSuperAdmin(Long userId) {
        return UserConstants.SUPER_ADMIN_ID.equals(userId);
    }

    public static boolean isSuperAdmin() {
        return isSuperAdmin(getUserId());
    }

    /**
     * 是否为超级管理员
     *
     * @param rolePermission 角色权限标识组
     * @return 结果
     */
    public static boolean isTenantAdmin(Set<String> rolePermission) {
        if (CollUtil.isEmpty(rolePermission)) {
            return false;
        }
        return rolePermission.contains(TenantConstants.TENANT_ADMIN_ROLE_KEY);
    }

    public static boolean isTenantAdmin() {
        Object value = getStorageIfAbsentSet(TENANT_ADMIN_KEY, () -> {
            return isTenantAdmin(getLoginUser().getRolePermission());
        });
        return Convert.toBool(value);
    }

    public static boolean isLogin() {
        try {
            return ObjectUtil.isNotNull(getLoginUser());
        } catch (Exception e) {
            return false;
        }
    }

    public static Object getStorageIfAbsentSet(String key, Supplier<Object> handle) {
        try {
            Object obj = SaHolder.getStorage().get(key);
            if (ObjectUtil.isNull(obj)) {
                obj = handle.get();
                SaHolder.getStorage().set(key, obj);
            }
            return obj;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取用户(多级缓存)
     */
    public static LoginUser getLoginUser() {
        return (LoginUser) getStorageIfAbsentSet(LOGIN_USER_KEY, () -> {
            SaSession session = StpUtil.getTokenSession();
            if (ObjectUtil.isNull(session)) {
                return null;
            }
            return session.get(LOGIN_USER_KEY);
        });
    }

    /**
     * 基于token获取用户信息
     *
     * @param token 用户token
     * @return 用户信息
     */
    public static LoginUser getLoginUser(String token) {
        SaSession session = StpUtil.getTokenSessionByToken(token);
        if (ObjectUtil.isNull(session)){
            return null;
        }
        return (LoginUser) session.get(LOGIN_USER_KEY);
    }

    /**
     * 获取租户ID
     */
    public static Long getTenantId() {
        return Convert.toLong(SaHolder.getContext().getRequest().getHeader(TENANT_ID));
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt());
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        return BCrypt.checkpw(rawPassword, encodedPassword);
    }

    /**
     * 私钥解密(解密前台公钥加密的密文)
     *
     * @param encodeStr 公钥加密的数据
     * @return 私钥解密出来的数据
     */
    public static String decryptWithPrivate(String encodeStr) {
        RSA priRsa = new RSA("MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAn/yZwBpb+H1lj2ThdKD9ghrY5RIWD8fx/YgbSSUIfVpT/yVqxDkIIxN6yBls5h9kVetGGzICatdX7lPUauScPQIDAQABAkAWPJDOL5u65Qr5rEbd5AZ4T+z3odTpKpxK5eENAJW2fmBOY4MyRfqLrzeZMORSJyooGoMp6JlT1i9o9hT0jAqNAiEAyqD5BAIssw2ngB2aAZoHcXRxExmWIBUusVmAIZsYsMsCIQDKIFJMHxFXCEaXwZ0VKDDlfuXGLOyJQrPF4pruO/DuFwIgcm2pcpwPxiYF25Hb8N+dKHMLkC+42fFcZwcWFuRRczUCIE+4H71WI4ioAu+ntUS67U4Wlplq7n/UhwLtNR3xFj1RAiBqApwHEFAEYMDL0KQKm5ooTtGbmfCcGSrAximVAqdCbg==", null);
        return priRsa.decryptStr(encodeStr, KeyType.PrivateKey);
    }

    /**
     * 登录
     *
     * @param loginUser 登录用户
     * @param model     验证模块 - 工具类
     */
    public static void login(LoginUser loginUser, SaLoginModel model) {
        model = ObjectUtil.defaultIfNull(model, new SaLoginModel());
        // 登录
        StpUtil.login(loginUser.getLoginId(), model
            .setExtra(USER_KEY, loginUser.getUserId())
            .setExtra(USER_NAME_KEY, loginUser.getUsername())
            .setExtra(DEPT_KEY, loginUser.getDeptId())
            .setExtra(DEPT_NAME_KEY, loginUser.getDeptName()));
        // 设置token的session
        StpUtil.getTokenSession().set(LOGIN_USER_KEY, loginUser);
    }

    /**
     * 获取用户昵称
     *
     * @return 用户昵称
     */
    public static String getNickName() {
        return getLoginUser().getNickname();
    }
}
